package com.kayt.cyberBar.cuser.business.dao.impl;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.kayt.cyberBar.common.PageData;
import com.kayt.cyberBar.common.dao.EntityDao;
import com.kayt.cyberBar.common.property.PublicCodeConfigInfo;
import com.kayt.cyberBar.cuser.business.dao.IUserDao;
import com.kayt.cyberBar.cuser.business.entity.po.BPosition;
import com.kayt.cyberBar.cuser.business.entity.po.BUser;
import com.kayt.cyberBar.cuser.business.entity.po.BUserPicture;

@Repository("userDao")
@Transactional
public class UserDaoImpl implements IUserDao {
	@Autowired
	private EntityDao entityDao;
	@Autowired
	private PublicCodeConfigInfo configInfo;

	@Override
	public Integer save(BUser entity) throws SQLException {
		if (entity != null) {
			entityDao.save(entity);
			return 0;
		} else {
			return -1;
		}
	}

	@Override
	public Integer update(BUser entity) throws SQLException {
		if (entity != null) {
			entityDao.update(entity);
			return 0;
		} else {
			return -1;
		}
	}

	@Override
	public Integer delete(Long id) {
		if (id != null) {
			BUser BUser = findById(id);
			if (BUser != null) {
				entityDao.delete(BUser);
				return 0;
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	}

	@Override
	public BUser findById(Long id) {
		if (id != null) {
			return entityDao.findById(id, BUser.class);
		} else {
			return null;
		}
	}

	@Override
	public PageData<BUser> findByPage(int pageNum, int pageSize, String hql, Object[] params,
			LinkedHashMap<String, String> orderMap) throws SQLException {
		return this.entityDao.getPagingData(BUser.class, pageNum, pageSize, hql, params, orderMap);
	}

	@Override
	public BUser findByCode(String userCode) throws SQLException {
		if (StringUtils.isNotEmpty(userCode)) {
			List<BUser> bUserList = entityDao.getPagingDataBySql(BUser.class, -1, -1,
					"select * from b_user where USER_CODE = '" + userCode + "'", null);
			if (bUserList != null && bUserList.size() == 1) {
				return bUserList.get(0);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Override
	public BUser findByAccount(String userAccount) throws SQLException {
		if (StringUtils.isNotEmpty(userAccount)) {
			List<BUser> bUserList = entityDao.getPagingDataBySql(BUser.class, -1, -1,
					"select * from b_user where ACCOUNT = '" + userAccount + "'", null);
			if (bUserList != null && bUserList.size() == 1) {
				return bUserList.get(0);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	@Override
	public PageData<BUser> findUsersByStoreAndDepart(Integer pageNum, Integer pageSize, String storeCode,
			String departCode) throws SQLException {
		String departSql = "";
		if(StringUtils.isNotEmpty(departCode)){
			departSql = "AND b2.DEPART_CODE = '" + departCode + "'";
		}
		String sql = "SELECT u.* FROM b_user u,b_organization_depart_user b1, b_organization_store_depart b2 "
				+ "WHERE u.USER_CODE = b1.USER_CODE AND b1.STORE_DEPART_CODE = b2.STORE_DEPART_CODE "
				+ departSql + " and b2.STORE_CODE = '" + storeCode
				+ "' and u.STATUS_CODE != '" + configInfo.getUserStatusDelete() + "'";
		String countSql = "SELECT count(*) as count FROM b_user u,b_organization_depart_user b1, b_organization_store_depart b2 "
				+ "WHERE u.USER_CODE = b1.USER_CODE AND b1.STORE_DEPART_CODE = b2.STORE_DEPART_CODE "
				+ departSql + " and b2.STORE_CODE = '" + storeCode
				+ "' and u.STATUS_CODE != '" + configInfo.getUserStatusDelete() + "'";
		List<BUser> userList = entityDao.getPagingDataBySql(BUser.class, pageNum, pageSize, sql, null);
		List<Map<String, Object>> countResult = entityDao.getPagingDataBySql(countSql, -1, -1, null);
		BigInteger count = (BigInteger) countResult.get(0).get("count");
		PageData<BUser> pageData = new PageData<>();
		pageData.setPageList(userList);
		pageData.setTotal(count.longValue());
		return pageData;
	}

	@Override
	public PageData<BUser> findUsersByStoreCode(Integer pageNum, Integer pageSize, String storeCode, String roleCode,
			List<String> notRoleCodeList) throws SQLException {
		String roleCodeNotInSql = "";
		String roleCodeSql = "";
		if (notRoleCodeList != null && notRoleCodeList.size() != 0) {
			Iterator<String> roleCodeIter = notRoleCodeList.iterator();
			while (roleCodeIter.hasNext()) {
				String code = roleCodeIter.next();
				if (StringUtils.isEmpty(roleCodeNotInSql)) {
					roleCodeNotInSql += " and ur.roleCode not in ('" + code + "'";
				} else {
					roleCodeNotInSql += ",'" + code + "'";
				}
			}
			roleCodeNotInSql += ")";
		}
		if (StringUtils.isNotEmpty(roleCode)) {
			roleCodeSql = " and ur.roleCode = '" + roleCode + "'";
		}
		String hql = "SELECT u as user FROM BUser u,BOrganizationDepartUser b1, BOrganizationStoreDepart b2 "
				+ " , BUserRole ur WHERE u.userCode = b1.userCode AND b1.storeDepartCode = b2.storeDepartCode "
				+ "AND b2.storeCode = '" + storeCode + "' and u.statusCode != '" + configInfo.getUserStatusDelete()
				+ "'" + roleCodeNotInSql + roleCodeSql + " and u.userCode = ur.userCode";
		String countSql = "SELECT count(u.id) as count from BUser u,BOrganizationDepartUser b1, BOrganizationStoreDepart b2 "
				+ " , BUserRole ur WHERE u.userCode = b1.userCode AND b1.storeDepartCode = b2.storeDepartCode "
				+ "AND b2.storeCode = '" + storeCode + "' and u.statusCode != '" + configInfo.getUserStatusDelete()
				+ "'" + roleCodeNotInSql + roleCodeSql + " and u.userCode = ur.userCode";
		List<Map<String, Object>> userList = entityDao.getPagingDataByHql(pageNum, pageSize, hql, null);
		List<Map<String, Object>> countResult = entityDao.getPagingDataByHql(-1, -1, countSql, null);
		Long count = (Long) countResult.get(0).get("count");
		PageData<BUser> pageData = new PageData<>();
		List<BUser> resultUser = new ArrayList<>();
		Iterator<Map<String, Object>> mapIter = userList.iterator();
		while (mapIter.hasNext()) {
			resultUser.add((BUser) mapIter.next().get("user"));
		}
		pageData.setPageList(resultUser);
		pageData.setTotal(count);
		return pageData;
	}

	@Override
	public Map<String, BUser> findUserMapByStoreCode(Integer pageNum, Integer pageSize, String storeCode)
			throws SQLException {
		PageData<BUser> pageDate = findUsersByStoreCode(pageNum, pageSize, storeCode, null, null);
		if (pageDate != null && pageDate.getTotal() != 0) {
			Map<String, BUser> userMap = new HashMap<>();
			List<BUser> userList = pageDate.getPageList();
			Iterator<BUser> userIter = userList.iterator();
			while (userIter.hasNext()) {
				BUser user = userIter.next();
				userMap.put(user.getUserCode(), user);
			}
			return userMap;
		} else {
			return new HashMap<String, BUser>();
		}
	}

	@Override
	public Map<String, String> getUserName(String storeCode) throws SQLException {
		Map<String, String> resultMap = new HashMap<>();
		String sql = "select uw.WORK_CODE,u.USER_NAME from b_user u ,b_organization_depart_user "
				+ "du,b_organization_store_depart sd ,b_sheet_user_work uw where u.USER_CODE = du.USER_CODE "
				+ "and sd.STORE_DEPART_CODE = du.STORE_DEPART_CODE and uw.USER_CODE = u.USER_CODE and sd.STORE_CODE = '"
				+ storeCode + "'";
		List<Map<String, Object>> dataMapList = entityDao.getPagingDataBySql(sql, -1, -1, null);
		if (dataMapList != null && dataMapList.size() != 0) {
			Iterator<Map<String, Object>> dataIter = dataMapList.iterator();
			while (dataIter.hasNext()) {
				Map<String, Object> data = dataIter.next();
				resultMap.put(data.get("WORK_CODE") == null ? "" : data.get("WORK_CODE").toString(),
						data.get("USER_NAME") == null ? "" : data.get("USER_NAME").toString());
			}
		}
		return resultMap;
	}

	@Override
	public BUser findByWorkCode(String workCode) throws SQLException {
		if (StringUtils.isNotEmpty(workCode)) {
			List<BUser> bUserList = entityDao.getPagingDataBySql(BUser.class, -1, -1,
					"select u.* from b_user u , b_sheet_user_work uw where u.USER_CODE = uw.USER_CODE and uw.WORK_CODE = '"
							+ workCode + "'",
					null);
			if (bUserList != null && bUserList.size() == 1) {
				return bUserList.get(0);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.kayt.cyberBar.cuser.business.dao.IUserDao#findUserInfo(java.lang.
	 * String, java.lang.String, java.lang.String, java.lang.String, int, int)
	 */
	@Override
	public PageData<Map<String, Object>> findUserInfo(String storeCode, String departCode, String roleCode,
			String userCode, int pageNum, int pageSize) throws SQLException {
		PageData<Map<String, Object>> page = new PageData<>();
		String userSql = "";
		if (StringUtils.isNotEmpty(userCode)) {
			userSql = " and u.userCode = '" + userCode + "'";
		} else if (StringUtils.isNotEmpty(roleCode)) {
			userSql = " and ur.roleCode = '" + roleCode + "'";
			userSql += " and sd.storeCode = '" + storeCode + "'";
		} else if (StringUtils.isNotEmpty(departCode)) {
			userSql = " and du.departCode = '" + departCode + "'";
			userSql += " and sd.storeCode = '" + storeCode + "'";
		} else if (StringUtils.isNotEmpty(storeCode)) {
			userSql = " and sd.storeCode = '" + storeCode + "'";
		}
		userSql += " and ur.roleCode != '" + configInfo.getUserRoleStoreManager() + "'";
		userSql += " and ur.roleCode != '" + configInfo.getUserRoleStoreBoss() + "'";
		String hql = "SELECT u.userCode as userCode,u.userName as userName,ur.roleCode as roleCode,sd.storeCode as storeCode,"
				+ "du.departCode as departCode, bp.picutreUrl as picutreUrl FROM BUser u, BUserPicture bp, BOrganizationDepartUser du, BOrganizationStoreDepart sd, BUserRole ur  "
				+ "WHERE u.userCode = du.userCode and du.storeDepartCode = sd.storeDepartCode and ur.userCode = u.userCode"
				+ " and u.userCode = bp.userCode and u.statusCode != '" + configInfo.getUserStatusDelete() + "'"
				+ userSql;
		String countSql = "SELECT count(u.id) as count FROM BUser u,BOrganizationDepartUser du, BOrganizationStoreDepart sd, BUserRole ur  "
				+ "WHERE u.userCode = du.userCode and du.storeDepartCode = sd.storeDepartCode and ur.userCode = u.userCode"
				+ " and u.statusCode != '" + configInfo.getUserStatusDelete() + "'" + userSql;
		List<Map<String, Object>> resultList = entityDao.getPagingDataByHql(-1, -1, hql, null);
		List<Map<String, Object>> countList = entityDao.getPagingDataByHql(-1, -1, countSql, null);
		if (countList != null && countList.size() != 0) {
			page.setPageList(resultList);
			Long total = (Long) countList.get(0).get("count");
			page.setTotal(total.longValue());
			return page;
		} else {
			return page;
		}
	}

	@Override
	public BUserPicture getUserPic(String userId) throws SQLException {
		if (StringUtils.isNotBlank(userId)) {
			return this.entityDao.getObj(BUserPicture.class, " o.userCode=? ", new Object[] { userId });
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kayt.cyberBar.cuser.business.dao.IUserDao#findByRole(java.lang.
	 * String, java.lang.String)
	 */
	@Override
	public List<BUser> findByRole(String storeCode, String roleCode) throws SQLException {
		if (StringUtils.isEmpty(roleCode))
			return new ArrayList<BUser>();
		String sql = "SELECT u.* FROM b_user u,b_organization_depart_user b1, b_organization_store_depart b2 "
				+ ",b_user_role ur WHERE u.USER_CODE = b1.USER_CODE AND b1.STORE_DEPART_CODE = b2.STORE_DEPART_CODE "
				+ " and u.USER_CODE = ur.USER_CODE and b2.STORE_CODE = '" + storeCode + " and ur.ROLE_CODE = '"
				+ roleCode + "' and u.STATUS_CODE != '" + configInfo.getUserStatusDelete() + "'";
		return entityDao.getPagingDataBySql(BUser.class, -1, -1, sql, null);
	}
}
